package cn.itcast.controller;

import cn.itcast.entity.Result;
import cn.itcast.massage.MessageConstant;
import cn.itcast.service.MemberService;
import cn.itcast.service.ReportService;
import cn.itcast.service.SetmealService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map map = new HashMap<>();
        List list = new ArrayList();
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH, -12);
            for (int i = 0; i < 12; i++) {
                calendar.add(Calendar.MONTH, 1);
                System.out.println(Calendar.MONTH);
                Date date = calendar.getTime();
                String format = new SimpleDateFormat("yyyy.MM").format(date);
                list.add(format);
                map.put("months", list);
            }
            List memberCount = memberService.findMemberCount(list);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Map map = new HashMap();
        try {
            List<Map> setmealList = setmealService.getSetmealReport();
            List setmealNamesList = new ArrayList();
            for (Map setmealMap : setmealList) {
                Object name = setmealMap.get("name");
                setmealNamesList.add(name);
                System.out.println(name);
            }
            map.put("setmealNames", setmealNamesList);
            map.put("setmealCount", setmealList);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> map = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public void exportBusinessReport(HttpServletRequest request, HttpServletResponse response) {
        ServletOutputStream outputStream = null;
        XSSFWorkbook workbook = null;
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");

            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            // 创建工作簿对象
            workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            // 获取sheet
            XSSFSheet sheet = workbook.getSheetAt(0);
            XSSFRow row2 = sheet.getRow(2);
            row2.getCell(5).setCellValue(reportDate);

            XSSFRow row4 = sheet.getRow(4);
            row4.getCell(5).setCellValue(todayNewMember);
            row4.getCell(7).setCellValue(totalMember);

            XSSFRow row5 = sheet.getRow(5);
            row5.getCell(5).setCellValue(thisWeekNewMember);
            row5.getCell(7).setCellValue(thisMonthNewMember);

            XSSFRow row7 = sheet.getRow(7);
            row7.getCell(5).setCellValue(todayOrderNumber);
            row7.getCell(7).setCellValue(todayVisitsNumber);

            XSSFRow row8 = sheet.getRow(8);
            row8.getCell(5).setCellValue(thisWeekOrderNumber);
            row8.getCell(7).setCellValue(thisWeekVisitsNumber);

            XSSFRow row9 = sheet.getRow(9);
            row9.getCell(5).setCellValue(thisMonthOrderNumber);
            row9.getCell(7).setCellValue(thisMonthVisitsNumber);

            Integer rows = 12;
            for (Map map : hotSetmeal) {
                XSSFRow row = sheet.getRow(rows);
                row.getCell(4).setCellValue((String) map.get("name"));
                row.getCell(5).setCellValue((Long) map.get("setmeal_count"));
                row.getCell(6).setCellValue((String) map.get("proportion"));
                rows++;
            }
            outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(outputStream);
            outputStream.flush();
        }catch (Exception e){
            e.printStackTrace();
        } finally {
            if (outputStream!=null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (workbook!=null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
